package top.zhangjianyong.tools.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StringUtil {

    /**
     * 分割字符串
     *
     * @param line
     * @param sp
     * @return
     */
    public static List<String> split(String line, String sp) {
        String[] split = line.split(sp);
        return Stream.of(split)
                .map(StringUtil::toString)
                .collect(Collectors.toList());

    }

    /**
     * 分割字符串，忽略引号中分割符
     *
     * @param line
     * @param sp
     * @return
     */
    public static List<String> regexSplit(String line, String sp) {
        String pattern = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(line);
        List<String> list = new ArrayList<>();
        int index = 0;
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            list.add(StringUtil.toString(line.substring(index, start)));
            index = end;
        }
        list.add(line.substring(index));
        return list;
    }

    public static String toString(String s) {
        return s == null ? "" : s.trim().replaceAll("\t", "");
    }

    /**
     * 去除字符串首尾出现的某个字符.
     *
     * @param source  源字符串.
     * @param element 需要去除的字符.
     * @return String.
     */
    public static String trimFirstAndLastChar(String source, String element) {
        if (source == null) return null;
        int beginIndex = source.indexOf(element);
        if (beginIndex == -1) return source;
        int endIndex = source.lastIndexOf(element);
        if (endIndex == beginIndex) return source;
        beginIndex = beginIndex + 1;
        return source.substring(beginIndex, endIndex);
    }

    public static List<String> trimFirstAndLastChar(List<String> lines, String element) {
        return lines.stream().map(line -> trimFirstAndLastChar(line, "\""))
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        Map<String, String> map = uriToMap("getPage_getShopRq.action?datecs=2022-10-04&cc=&bizid=11001");

        System.out.println(JSONObject.toJSONString(map));
    }

    public static Map<String, String> uriToMap(String uri) {
        String[] split = uri.split("\\?")[1].split("&");
        Map<String, String> map = new HashMap<>();
        for (String s:split){
            String[] entry = s.split("=",-1);
            map.put(entry[0],entry[1]);
        }
        return map;
    }


}
